import random
import string

from OpenAIUtils.OpenAIUtils import get_completion, get_content, get_instruct_completion
from OpenAIUtils.PromptTemplate import PromptTemplate
from OpenAIUtils.OutputParser import parse_json, parse_str
from .PlaceholderUtils import *
from .Paraphraser import random_whitespaces


class Translator:
    def __init__(self, template_file, model="gpt-3.5-turbo", temperature=0.9):
        self.prompt_template = PromptTemplate().from_file(template_file)
        self.model = model
        self.temperature = temperature

    def run(self, text):
        if len(text.strip()) == 0:
            return random_whitespaces(num_results=1)[0]

        if all(char in string.punctuation for char in text):
            return ''.join([random.choice(string.punctuation)] * len(text))

        placeholders = extract_placeholders(text)
        for placeholder in placeholders:
            text = text.replace(placeholder, "{}")
        prompt = self.prompt_template.get_prompt(text=text)
        seed = random.randint(0, 2^32-1)
        if "instruct" in self.model:
            response = get_instruct_completion(self.model, prompt, temperature=self.temperature, seed=seed)
        else:
            response = get_completion(self.model, prompt, temperature=self.temperature, seed=seed)
        content = get_content(response)
        ret = parse_str(content)
        ret = restore_placeholders(ret, placeholders)
        return ret

